package com.wiwl.web.controller;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import com.wiwl.security.Role;
import com.wiwl.security.User;
import com.wiwl.service.ServiceLocator;

public class MenuTag extends TagSupport {

  private String basePath;
  private Collection<GrantedAuthority> userRoles;
  
  
  @Override
  public int doStartTag() throws JspException {
    JspWriter out =  pageContext.getOut();
    init();
    try {
      out.println(drawMenu());
    } catch (IOException e) {
      throw new RuntimeException("error creting menu");
    }
    
    return SKIP_BODY;
  }

private void init() {
	basePath = 	pageContext.getServletContext().getContextPath();
    User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	userRoles = user.getAuthorities();
}

  private String drawMenu(){
	    List<MenuItem> menuItems = ServiceLocator.getMenuItemService().getRootMenuItems();
	    StringBuffer buffer = new StringBuffer();
	    buffer.append("<div class=\"menu\">");
	    
	      getHTML(menuItems, buffer);
	    
	    buffer.append("</div>");
	    return buffer.toString();
	  }

  private void getHTML(List<MenuItem> menuItems, StringBuffer buffer) {
	  buffer.append("<ul>");
	  for(MenuItem item: menuItems){
		  if(hasPermission(item.getRoles())){
			  drawMenuItem(item, buffer);
		  }
	  }
	  buffer.append("</ul>");
  }

  private void drawMenuItem(MenuItem item, StringBuffer buffer) {
	buffer.append("<li>");
	String href =  item.getUrl()!= null && !"".equals(item.getUrl())? item.getUrl(): "";
	buffer.append("<a onclick=\"openUrl('"+	basePath+href+"');\">"+item.getDescription()+"</a>");
	if(item.getChildMenuitems() != null && !item.getChildMenuitems().isEmpty()){
		getHTML(item.getChildMenuitems(), buffer);
	}
	buffer.append("</li>");
  }
  
  private boolean hasPermission(List<Role> roles) {
	  
	  for(Role role: roles){
		  if(userRoles.contains(role)){
			  return true;
		  }
	  }
	  return roles == null || roles.isEmpty()? true : false;
	}
  
}
